package com.usian.user.service.impl

import com.alibaba.fastjson.JSON
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.usian.common.BaseServiceImpl
import com.usian.common.constants.behavior.FollowBehaviorConstants
import com.usian.model.behavior.dto.FollowBehaviorDto
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.common.enums.AppHttpCodeEnum
import com.usian.model.user.dtos.UserRelationDto
import com.usian.model.user.pojos.ApUser
import com.usian.model.user.pojos.ApUserFan
import com.usian.model.user.pojos.ApUserFollow
import com.usian.user.feign.ArticleFeign
import com.usian.user.mapper.ApUserFanMapper
import com.usian.user.mapper.ApUserFollowMapper
import com.usian.user.mapper.ApUserMapper
import com.usian.utils.threadlocal.AppThreadLocalUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*


@Service
@Transactional
open class UserRelationServiceImpl : BaseServiceImpl<ApUserMapper, ApUser>() {
    @Autowired
    lateinit var apUserFollowMapper: ApUserFollowMapper

    @Autowired
    lateinit var apUserFanMapper: ApUserFanMapper

    @Autowired
    lateinit var articleFeign: ArticleFeign

    @Autowired
    lateinit var kafkaTemplate: KafkaTemplate<String,String>

    open fun follow(dto: UserRelationDto): ResponseResult<*> {
        dto.operation.let {
            if (it == null || it < 0 || it > 1) return errorResult
        }
        if (dto.articleId == null) return errorResult
        var followId: Int? = null
        val author = articleFeign.selectById(dto.authorId)
        if (author != null) followId = author.userId
        return if (followId != null) {
            var apUser = AppThreadLocalUtils.getUser()
            if (apUser != null)//登录了
                if (dto.operation.toInt() == 0) followByUserId(apUser, followId, dto.articleId)
                else followCancelByUserId(apUser, followId)
            else ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)
        } else noData
    }

    private fun followCancelByUserId(apUser: ApUser, followId: Int): ResponseResult<*> {
        val followW = Wrappers.query<ApUserFollow>().eq("userId", apUser.id).eq("followId", followId)
        val userFollow = apUserFollowMapper.selectOne(followW)
        return if (userFollow == null) ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "未关注") else {
            val fanW = Wrappers.query<ApUserFan>().eq("userId", followId).eq("fansId", apUser.id)
            val userfan = apUserFanMapper.selectOne(fanW)
            if (userfan != null){
                apUserFanMapper.delete(fanW)
            }
            apUserFollowMapper.delete(followW)
            sucResult
        }
    }

    private fun followByUserId(apUser: ApUser, followId: Int, articleId: Long?): ResponseResult<*> {
        val followUser = baseMapper.selectById(followId) ?: return noData
        val eq1:QueryWrapper<ApUserFollow> = QueryWrapper()
        eq1.eq("follow_id", followId)
        val userFollow = apUserFollowMapper.selectOne(eq1)
        if (userFollow == null) {
            val eq = Wrappers.query<ApUserFan>().eq("user_id", followId).eq("fans_id", apUser.id)
            val userFan = apUserFanMapper.selectOne(eq)
            if (userFan == null) {
                apUserFanMapper.insert(ApUserFan().apply {
                    userId = followId
                    fansId = apUser.id.toLong()
                    fansName = followUser.name
                    level = 0
                    isDisplay = true
                    isShieldLetter = false
                    createdTime = Date()
                })
            }
            apUserFollowMapper.insert(ApUserFollow().apply {
                userId = apUser.id
                this.followId = followId
                createdTime = Date()
                isNotice = true
                level = 1
            })
            kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC,JSON.toJSONString(FollowBehaviorDto().apply {
                this.articleId = articleId
                this.followId = followId
                userId = apUser.id
            }))
            return sucResult
        } else return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已关注")
    }
}
